﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TaoPortal.BusinessLogic.DTO;
using TaoPortal.BusinessLogic.Extensions;
using TaoPortal.DataAccess;
using TaoPortal.Entity;

namespace TaoPortal.BusinessLogic.Repository
{
    public class FileRepository : BaseRepository
    {
        public FileRepository(DataContext dbcontext)
        {
            db = dbcontext;
            AutoCommit = true;
        }

        public FileRepository()
            : this(new DataContext())
        {

        }

        public void SaveFile(TP_SysFile file)
        {
            db.TP_SysFile.Add(file);
            SaveChanges();
        }

        public void DeleteFile(string fileid)
        {
            db.Entry<TP_SysFile>(new TP_SysFile { ID = fileid }).State = System.Data.Entity.EntityState.Deleted;
            SaveChanges();
        }

        public TP_SysFile GetFile(string fileid)
        {
            return db.TP_SysFile.Where(f => f.ID == fileid).FirstOrDefault();
        }

        public SimpleFile GetSimpleFile(string fileid)
        {
            return db.TP_SysFile.Where(f => f.ID == fileid).Select(f => new SimpleFile
            {
                ID = f.ID,
                CreateBy = f.CreateBy,
                CreateTime = f.CreateTime,
                FClassID = f.FClassID,
                FExtName = f.FExtName,
                FLength = f.FLength,
                FName = f.FName,
                FType = f.FType,
                Remark = f.Remark,
                Sort = f.Sort
            }).FirstOrDefault();
        }

        public PagedList<SimpleFile> GetFileList(string fClassID, string fName, DateTime? startDate, DateTime? endDate, int pageIndex, int pageSize)
        {
            var d = (from f in db.TP_SysFile
                     where f.FClassID == fClassID
                     orderby f.CreateTime descending
                     select new SimpleFile
                     {
                         ID = f.ID,
                         CreateBy = f.CreateBy,
                         CreateTime = f.CreateTime,
                         FClassID = f.FClassID,
                         FExtName = f.FExtName,
                         FLength = f.FLength,
                         FName = f.FName,
                         FType = f.FType,
                         Remark = f.Remark,
                         Sort = f.Sort
                     });
            if (!string.IsNullOrEmpty(fName))
            {
                d = d.Where(x => x.FName.Contains(fName));
            }
            if (startDate != null)
            {
                d = d.Where(x => x.CreateTime >= startDate);
            }
            if (endDate != null)
            {
                d = d.Where(x => x.CreateTime <= endDate);
            }
            return d.ToPagedList(pageIndex, pageSize);
        }

    }
}
